<template>
  <div class="zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t('年') }}</p>
            <div class="ipt">
              <DatePicker v-model="searchParams.year" type="year"
                          :placeholder="`${$t('common.selectInfo')}`"></DatePicker>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('年月') }}</p>
            <div class="ipt">
              <DatePicker v-model="searchParams.month" type="month"
                          :placeholder="`${$t('common.selectInfo')}`"></DatePicker>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="changeNum()">{{ $t('common.Query') }}</Button>
              <Button
                  class="reset-btn"
                  @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="addClickinfo" v-has="'billManagementAdd'">{{ $t('common.New') }}</Button>
        <Button @click="exportTemplateClick" v-has="'billManagementExport'">{{ $t('common.batchExport') }}</Button>
        <Button @click="importExcelShow" v-has="'billManagementImport'">{{ $t('common.Import') }}</Button>
        <Button @click="exportTemplate" v-has="'billManagementDown'">{{ $t('common.Download') }}</Button>
        <Button @click="deleteAll" v-has="'billManagementDeleteAll'">{{ $t('common.batchDelete') }}</Button>
        <Button @click="downYearTemplate" v-has="'downloadFactoryCalendarTemplate'">{{ $t('下载工厂年历模板') }}</Button>
        <Button @click="exportYearTemplate" v-has="'downloadFactoryCalendarTemplate'">{{ $t('导入工厂年历模板') }}</Button>
          <Button @click="getTableColumns(columns)">
              {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
          </Button>
      </div>
      <div class="tableContent">
        <Table
            class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList"
            :data="dataSource"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" v-has="'billManagementEdit'" @click="addClickinfo(row)"><i
                class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}</span>
            <span
                class="operationBtn"
                v-has="'billManagementDelete'"
                @click="(deleteModal = true), (deleteIds = [row.id])"
            ><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
            <span class="operationBtn" v-has="'AccountClosingManagementDetail'" @click="lookDetail(row)"><i
                class="iconfont zy-common-bianji"></i>{{ $t('详情') }}</span>
          </template>
        </Table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="deleteIds.length"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="$variable.pageSizes"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
    <Modal :mask-closable="false" v-model="addModal" class="modal-content-layout" :title="addtitle">
      <Form
          ref="billFormValidate"
          class="formList"
          :model="formItem"
          :rules="rules"
          label-position="top"
      >
        <FormItem :label="$t('年月')" prop="month">
          <DatePicker v-model="formItem.month" type="month" :placeholder="`${$t('common.selectInfo')}`"></DatePicker>
        </FormItem>
        <FormItem :label="$t('关账时间')" prop="date">
          <DatePicker v-model="formItem.date" type="daterange" :placeholder="`${$t('common.selectInfo')}`"></DatePicker>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="addModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="handleSubmit('billFormValidate')">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="deleteModal" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.confirmDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="handleDelete">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <importExcelModal
        :importExcelStateF="importExcelState"
        v-if="importExcelState"
        :url="exportTemplateUrl"
        @importExcelChange="importExcelChange"
    ></importExcelModal>
    <Modal :mask-closable="false" width="800px" v-model="factoryCalendarShow" class="modal-content-layout" :title="$t('详情')">
      <div>
        <Tabs class="tabs-layout" v-model="factoryCalendarIndex" @on-click="onYearChange">
          <TabPane v-for="(item,index) in Object.keys(listFactoryCalendar)" :label="item" :name="item" :key="index" >
            <ACalendar v-model="calendarValue" :headerRender="headerRender" :locale="locale">
              <div class="dayBox" slot="dateFullCellRender" slot-scope="value">

                <div v-if="checkDayWork(value)" class="defaultWorkDay activeWorkDay">
                  <span>{{ $moment(value).format('DD') }}</span>
                  <span>工作日</span>
                </div>
                <div class="defaultWorkDay" v-else>
                  <span>{{ $moment(value).format('DD') }}</span>
                  <span>--</span>
                </div>
              </div>
            </ACalendar>
          </TabPane>
        </Tabs>
      </div>
    </Modal>
  </div>
</template>

<script>
import fileDownload from "js-file-download";
import importExcelModal from "@/components/importExcel.vue";
import {Calendar} from 'ant-design-vue';
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "faultClassify",
  components: {importExcelModal, ACalendar: Calendar},
    mixins:[toggleTableOperation],
  data() {
    return {
      headerRender: ()=>{},
      factoryCalendarIndex:"",
      factoryCalendarLabelList:[],
      locale: {lang:{locale:this.$i18n.locale}},
      factoryCalendarShow: false,
      searchParams: {
        year: '',
        month: ''
      },
      total: 0, // 总数
      pageNum: 1, // 页数
      pageSize: 12, // 每页的个数
      pageSizeOption: [12, 24, 36],
      addModal: false, // 新增弹窗
      addtitle: "", // 新增/编辑 标题
      formItem: {
        month: '',
        date: []
      },
      rules: { // 校验规则
        month: [
          {required: true, type: 'date', message: this.$t('common.selectInfo'), trigger: "change"},
        ],
        date: [
          {required: true, type: 'array', message: this.$t('common.selectInfo'), trigger: "change"},
        ],
      },
      deleteModal: false, // 删除弹窗
      deleteIds: [], // 删除Id
      importExcelState: false, // 导入弹窗
      checkBtnPermission: {}, // 按钮权限
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: `${this.$t('年')}`,
          key: "year",
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('年月')}`,
          key: "month",
          align: "center",
            resizable: true
        },
        {
          // title: "关账时间",
          title: `${this.$t('关账时间')}`,
          key: "yearMonthStr",
          align: "center",
            resizable: true
        },
        {
          // title: "创建人",
          title: `${this.$t('创建人')}`,
          key: "createName",
          align: "center",
            resizable: true
        },
        {
          // title: "创建时间",
          title: `${this.$t('创建时间')}`,
          key: "createTime",
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          align: "center",
          width: this.util.autoWidth(250, 300)
        },
      ],
      dataSource: [],
      exportTemplateUrl: "",
      listFactoryCalendar: [],
      calendarValue:""
    };
  },
  created() {
      this.getTableColumnsWidth(this.columns)
    this.searchList();
  },
  methods: {
    onYearChange(){
      this.calendarValue = this.$moment(new Date(this.listFactoryCalendar[this.factoryCalendarIndex][0].day))
    },
    lookDetail(row) {
      this.axios({
        method: "get",
        url: `/dms//year/month/listFactoryCalendar`,
        params: {basicYearMonthId: row.id},
      }).then((res) => {
        if (res.code === 200) {
          const obj = res.data;
          if (Object.keys(obj).length > 0){
            this.listFactoryCalendar = obj;
            this.factoryCalendarIndex = Object.keys(obj)[0]
            this.calendarValue = this.$moment(new Date(obj[this.factoryCalendarIndex][0].day))
            // if (Array.isArray(this.listFactoryCalendar) && this.listFactoryCalendar.length > 0)
            // {
            this.factoryCalendarShow = true
            // }else{

            // }
          }else{
              this.$Message.warning({
                content: this.$t('暂无数据'),
                duration: 6,
                closable: true,
              });
          }

        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    checkDayWork(val) {
      return this.listFactoryCalendar[this.factoryCalendarIndex].find(item => {
        return item.day === this.$moment(val).format('YYYY-MM-DD') && item.ifWorkday==1
      })
    },
    addClickinfo(row = {}) {
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`;
        this.formItem = {
          month: row.month,
          date: [row.startDate, row.endDate],
          id: row.id,
        };
      } else {
        this.addtitle = `${this.$t('common.New')}`;
        this.formItem = {
          month: '',
          date: []
        }
        this.$refs['billFormValidate'].resetFields()
      }
      this.addModal = true;
    },
    // 新增提交
    handleSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const params = {
            month: this.$moment(this.formItem.month).format('YYYY-MM'),
            startDate: this.$moment(this.formItem.date[0]).format('YYYY-MM-DD'),
            endDate: this.$moment(this.formItem.date[1]).format('YYYY-MM-DD'),
          };
          if (this.formItem.id) params.id = this.formItem.id;
          this.axios({
            method: "post",
            url: `/dms/year/month/${
                this.formItem.id ? "edit" : "add"
            }`,
            data: params,
          }).then((res) => {
            if (res.code === 200) {
              this.addModal = false;
              this.$Message.success(res.msg);
              this.changeNum();
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          });
        }
      });
    },
    // 删除操作
    handleDelete() {
      this.axios({
        method: "get",
        url: "/dms/year/month/delete",
        params: {ids: this.deleteIds.join(',')},
      }).then((res) => {
        if (res.code === 200) {
          this.deleteModal = false;
          this.$Message.success(res.msg);
          this.changeNum();
          this.deleteIds = []
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        year: this.searchParams.year ? this.$moment(this.searchParams.year).format('YYYY') : '',
        month: this.searchParams.month ? this.$moment(this.searchParams.month).format('YYYY-MM') : '',
      };
      this.axios({
        method: "get",
        url: "/dms/year/month/list",
        params,
      }).then((res) => {
        if (res.code === 200) {
          this.dataSource = res.data.list;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    onSelectChange(selection) {
      this.deleteIds = selection.map((item) => item.id);
    },
    //下载模板
    exportTemplate() {
      const filName = `${this.$t('关账管理')}${this.$t('common.Download')}`;
      this.axios({
        method: "get",
        url: "/dms/year/month/exportTemplate",
        responseType: "blob",
      }).then((res) => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    downYearTemplate() {
      const filName = `${this.$t('工厂年历模板')}`;
      this.axios({
        method: "get",
        url: "/dms/year/month/exportFactoryCalendarTemplate",
        responseType: "blob",
      }).then((res) => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    //导出
    exportTemplateClick() {
      let params = {
        year: this.searchParams.year ? this.$moment(this.searchParams.year).format('YYYY') : '',
        month: this.searchParams.month ? this.$moment(this.searchParams.month).format('YYYY-MM') : '',
        ids: this.deleteIds.join(','),
      };
      const filName = this.$t('关账管理');
      this.axios({
        method: "get",
        url: "/dms/year/month/export",
        responseType: "blob",
        params: params,
      }).then((res) => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    /*导入*/
    importExcelShow() {
      this.exportTemplateUrl = ""
      this.importExcelState = true;
    },
    exportYearTemplate() {
      const isTong = process.env.NODE_ENV === 'tong';
      let ksiot = '/kakone';
      if (isTong) {
        ksiot = ''
      }
      this.exportTemplateUrl = ksiot + "/dms/year/month/importFactoryCalendar"
      this.importExcelState = true;
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === "success") {
        // this.$Message.success("导入成功");
        this.changeNum();
      }
    },
    // 批量删除
    deleteAll() {
      if (this.deleteIds.length == 0) {
        this.$Message.warning({
          content: `${this.$t('common.deleteItems')}`,
          duration: 6,
          closable: true,
        });
        return;
      } else {
        this.deleteModal = true;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.defaultWorkDay {
  text-align: center;
  padding: 10px 0;
  background: #fff;

  span {
    display: block;
    color: #666;
    font-weight: bold;
  }
}

.activeWorkDay {
  text-align: center;
  padding: 10px 0;
  background: #e6f7ff;

  span {
    display: block;
    color: #1890ff;
    font-weight: bold;
  }
}

/deep/ .ant-fullcalendar-column-header-inner {
  text-align: center;
  color: #00142D;
  font-weight: bold;
  font-size: 15px;
}
/deep/ .ant-fullcalendar-last-month-cell,.ant-fullcalendar-next-month-btn-day{
  .defaultWorkDay {
    span {
      color: rgba(171, 171, 171,1);
    }
  }
}
</style>


